//
//  HomeHeaderView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/3.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import TYAttributedLabel

protocol HomeVideoHeaderViewDelegate: NSObjectProtocol {
    func reloadSuperTableView(view: ConsultationHeaderView)
    
    func updateAttention(isAttention:Bool)
}

class HomeVideoHeaderView: UITableViewHeaderFooterView, SBPlayerDelegate, AddCornerUIRectCorner, BottomShadow {

    let sideMargin: CGFloat = 27

    @IBOutlet weak var collectionWithTopView: NSLayoutConstraint!
    
    @IBOutlet weak var userContentView: UIView!
    @IBOutlet weak var userInfoHeight: NSLayoutConstraint!
    @IBOutlet weak var userHeaderBGImageView: UIImageView!
    @IBOutlet weak var userAvatarImageView: UIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var userLevelLabel: UILabel!
    @IBOutlet weak var percentageLabel: UILabel!
    @IBOutlet weak var userConstellationLabel: UILabel!
    @IBOutlet weak var bPlayer: SBPlayer!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var introductionLabel: TYAttributedLabel!
    @IBOutlet weak var titleLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var introductionHeight: NSLayoutConstraint!
    @IBOutlet weak var titleLabel: TYAttributedLabel!
    @IBOutlet weak var followButton: UIButton!

    @IBOutlet weak var tagScrollView: TagScrollView!
    @IBOutlet weak var itemsCollectionView: RecommendCollectionView!
    @IBOutlet weak var commentCountLabel: UILabel!
    @IBOutlet weak var commentCountView: UIView!
    weak var delegate: HomeVideoHeaderViewDelegate?

    var delegateVc: UIViewController?
    var videoADView: VideoADView?
    /// 通过xib获取当前View
    ///
    /// - Returns: self
    func instanceHomeVideoHeaderView() -> HomeVideoHeaderView {
        let array = Bundle.main.loadNibNamed("\(HomeVideoHeaderView.self)", owner: self, options: nil)
        let view = array?.first as! HomeVideoHeaderView
        return view
    }
    
    override func awakeFromNib() {
        setUI()
    }
    
    private func setUI() {
        let type:String = UIDevice.current.model
        if type == "iPad" {
            userHeaderBGImageView.isHidden = true
            userContentView.backgroundColor = UIColor.lightGray
        }
        followButton.layer.cornerRadius = followButton.height / 2
        followButton.layer.borderColor = UIColor.lightGray.cgColor
        followButton.layer.borderWidth = 2.0
        self.bPlayer.beforView = self
        let height = self.bPlayer.height + self.topView.height + 20 + self.itemsCollectionView.height + 10 + self.commentCountView.height + kHeight(r: 60) + 10
        self.height = height
       
//        self.addCornerWithView(aView: self.commentCountView, aCorners: [.topLeft,.topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        titleLabel.textColor = ONColor.normalTextColor
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        introductionLabel.textColor = ONColor.subTextColor
        introductionLabel.font = UIFont.systemFont(ofSize: 13)
        
//        setShadow(view: topView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
//        itemsCollectionView.contentOffset = .zero
    }
    
    func setData(model: VideoModel) {
        if model.author?.type == "internal" {
            userContentView.isHidden = true
            userInfoHeight.constant = 0
        }
        if let headicon = model.author?.headIcon {
            let headPath:String = "\(BaseURL)\(headicon )"
            let headurl = URL(string: headPath)!
            userAvatarImageView.sd_setImage(with: headurl as URL, completed: nil)
            userHeaderBGImageView.sd_setImage(with: headurl as URL, completed: nil)
            
        }
        
        if let username = model.author?.nickname{
            userName.text = username
        }
        if let level = model.author?.grade?.gradeCode{
            userLevelLabel.text = level
        }
        if let match = model.author?.matchDegree{
            percentageLabel.text = match
        }
        if let constellation = model.author?.constellation{
            userConstellationLabel.text = constellation
        }
        
        if model.author?.concernType! == "1"{
            self.followButton.isSelected = true
        }else {
            self.followButton.isSelected = false
        }
         itemsCollectionView.delegateVc = self.delegateVc
        if let videoFile = model.videoFilePath {
            bPlayer.asset(with: appendUrl(suffix: videoFile))
        }
        bPlayer.isHidden = false;
        bPlayer.backgroundColor = UIColor.black
        bPlayer.delegate = self
        if let summary = model.summary {
            introductionLabel.text = model.summary!
            titleLabel.appendTextAttributedString(NSAttributedString(string: model.title!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14)]))
            titleLabel.appendTextAttributedString(NSAttributedString(string: "  "+model.publishTime!, attributes: [NSAttributedStringKey.foregroundColor : ONColor.subTextColor, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10)]))
        }
        
        titleLabelHeight.constant = CGFloat(titleLabel.getHeightWithWidth(ScreenWidth - sideMargin * 2))
        introductionHeight.constant = CGFloat(introductionLabel.getHeightWithWidth(ScreenWidth - sideMargin * 2))
        
        if let labels = model.labels{
            var labelstr :[String] = []
            for  object in labels{
                labelstr.append(object.name!)
                
            }
            print(labelstr)
            tagScrollView.showData(titles: labelstr, labelColor: ONColor.subTextColor, fontSize: 10) { tag in
                
            }
        }
        setSelfHeight()
    }
    func updateItemsCollectionView(arr:[SearchRecommendModel]) -> Void {
        itemsCollectionView.setData(arr: arr)
    }
    func updateCommentTotalCount(count:Int) -> Void {
        commentCountLabel.text = "(" + String(count) + ")"
    }
    func updateAttentionState(attention:Bool) -> Void {
        followButton.isSelected = attention
    }
    
    func controlViewIsRight(_ isRight: Bool) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.isLandscape = !isRight
        if isRight {
            self.videoADView?.removeFromSuperview()
            // MARK: - 这句很重要
            let unknownValue = UIInterfaceOrientation.unknown.rawValue
            UIDevice.current.setValue(unknownValue, forKey: "orientation")
            // 将视图还原成竖屏
            let orientationTarget = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(orientationTarget, forKey: "orientation")
        } else {
            if bPlayer.verticalVideo {
                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.isLandscape = true
                let value = UIInterfaceOrientation.portrait.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
            }else {
                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.isLandscape = true
                let value = UIInterfaceOrientation.landscapeRight.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
            }
//            showVideoADView()
        }
    }
    @IBAction func attentionAction(_ sender: UIButton) {
        
        guard MineInfoModel.share.hasLoginIn() else {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            if let dele = self.delegate as? UIViewController {
                dele.navigationController?.pushViewController(loginVC, animated: true)
            }
            return
        }
        self.delegate?.updateAttention(isAttention: sender.isSelected)
    }
    deinit {
        if bPlayer != nil {
            bPlayer.pause()
//            bPlayer.removeFromSuperview()
        }
    }
    
    private func setSelfHeight() {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
            DispatchQueue.main.async {
              
                let height = self.bPlayer.height + self.topView.height + 20 + self.itemsCollectionView.height + 10 + self.commentCountView.height + self.userInfoHeight.constant + 10
                self.height = height
            }
        }
    }
    
    @IBAction func moreTap(_ sender: UIButton) {
        
    }

    // MARK: - 设置旋转后的view
    func showVideoADView() {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2) {
            DispatchQueue.main.async {
                if self.videoADView?.superview == nil {
                    self.videoADView = VideoADView()
                    self.videoADView?.showData(data: ["aaa"])
                }
               
            }
        }
    }
}

